package com.cskaoyan.util;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.data.*;
import com.cskaoyan.service.LogService;
import com.cskaoyan.service.LogServiceImpl;
import lombok.SneakyThrows;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author stone
 * @date 2023/03/31 17:09
 */
public class DispatchUtil {

    private static LogService logService = new LogServiceImpl();

    @SneakyThrows
    public static void dispatch(HttpServletRequest request, HttpServletResponse response, HttpServlet instance) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        String requestURI = request.getRequestURI();
        String operation = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        try{operation=operation.replace("-", "");}catch (Exception e){}
        //dispatch(operation,request,response,userServlet);
        Method method = instance.getClass().getDeclaredMethod(operation, HttpServletRequest.class, HttpServletResponse.class);
        method.setAccessible(true);
        Object invoke = method.invoke(instance, new Object[]{request, response});
        if (invoke != null && invoke instanceof BaseRespVo) {
            log(request, (BaseRespVo) invoke);
            ResponseUtil.responseJson(response, (BaseRespVo) invoke);
        }
    }

    //新增的添加日志方法
    @SneakyThrows
    private static void log(HttpServletRequest request, BaseRespVo invoke) {
        //获取操作名
        String uri = request.getRequestURI();
        String operation = uri.substring(uri.lastIndexOf("/") + 1);
        String object = uri.substring(7, uri.lastIndexOf("/"));
        String cnOperation = OperationPropertiesUtil.getValue(operation);
        String cnObject = ObjectPropertiesUtil.getValue(object);
        if (StringUtil.isEmpty(cnOperation) || StringUtil.isEmpty(cnObject))
            return;
        String action = cnObject + "-" + cnOperation;

        //获取管理员名
        MarketAdmin marketAdmin = null;
        String username = null;
        try {
            marketAdmin = (MarketAdmin) AuthenticationUtil.getPrincipal();
            username = marketAdmin.getUsername();
        } catch (Exception e) {
            LoginUserData loginUserData = (LoginUserData) invoke.getData();
            AdminInfoBean adminInfo = loginUserData.getUserInfo();
            username = adminInfo.getNickName();
        }

        //获取操作结果
        String result = null;
        Object resultVo = invoke.getData();
        try {
            if (resultVo instanceof MarketStorage) {
                result = "文件名称：" + ((MarketStorage) resultVo).getName() + "    文件类型：" + ((MarketStorage) resultVo).getType();
            } else if (resultVo instanceof ResGoodsCreateData) {
                result = "商品名称：" + ((ResGoodsCreateData) resultVo).getGoods().getName() + "    商品编号：" + (((ResGoodsCreateData) resultVo).getGoods().getGoodsSn());
            } else if (resultVo instanceof MarketGoods) {
                result = "商品名称：" + ((MarketGoods) resultVo).getName() + "    商品编号：" + (((MarketGoods) resultVo).getGoodsSn());
            } else if (resultVo instanceof MarketBrand) {
                result = "品牌名称：" + ((MarketBrand) resultVo).getName();
            } else if (resultVo instanceof MarketAd) {
                result = "广告名称：" + ((MarketAd) resultVo).getName();
            } else if (resultVo instanceof MarketCategory) {
                result = "品类名称：" + ((MarketCategory) resultVo).getName();
            } else if (resultVo instanceof MarketTopic) {
                result = "专题：" + ((MarketTopic) resultVo).getTitle();
            }
            // else if (resultVo instanceof MarketOrder) {
            //     result = "订单编号：" + ((MarketOrder) resultVo).getOrderSn();
            // }订单相关servlet写的过于复杂且不返回Vo
            else if (resultVo instanceof ResRefundData) {
                result = "订单号：" + ((ResRefundData) resultVo).getOrderId() + "    退款金额：" + (((ResRefundData) resultVo).getRefundMoney());
            } else if (resultVo instanceof ResShipData) {
                result = "物流公司：" + ((ResShipData) resultVo).getShipChannel() + "    物流编码：" + (((ResShipData) resultVo).getShipSn());
            } else if (resultVo instanceof MarketCoupon) {
                result = "优惠券名称：" + ((MarketCoupon) resultVo).getName();
            } else if (resultVo instanceof MarketAdmin) {
                result = "管理员ID：" + ((MarketAdmin) resultVo).getId().toString() + "    管理员名称：" + ((MarketAdmin) resultVo).getUsername();
            } else if (resultVo instanceof MarketUser) {
                result = "会员ID：" + ((MarketUser) resultVo).getId().toString() + "    会员名称：" + ((MarketUser) resultVo).getUsername();
            } else if (resultVo instanceof LoginUserData) {
                result = "登陆成功，管理员名称：" + ((LoginUserData) resultVo).getUserInfo().getNickName();
            } else if (resultVo == null) {
                result = invoke.getErrmsg();
            }
        } catch (Exception e) {
        }

        //获取其他信息
        String remoteAddr = request.getRemoteAddr();
        Date addTime = new Date();
        Integer type = 1;
        Boolean status = "成功".equals(invoke.getErrmsg());
        String comment = "这是备注";
        logService.log(username, remoteAddr, addTime, type, action, status, result, comment);
    }
}